package Teacher.Course;

import java.awt.event.*;
import java.sql.*;

import Database.*;
import Exception.*;
import General.*;

public class PanelCourse extends ManagementPanel
{
	private int selectedRow;
	
	public PanelCourse(CallDB callDB, Connection connection) throws CheckDataException, FormatScrollPaneException
	{
		super(callDB, connection);
		
		enableButton(false);
		
		createComponent();
		showComponent();
	}
	
	public void deleteCourse() throws NumberFormatException, EraseDataException, InsertionDataException, CheckDataException, Layer8TableException, FormatScrollPaneException, LoadDriverException
	{
		new CourseMgmt(connection).deleteElement((int)GeneralInformation.getCourseLeftModel().getValueAt(selectedRow, 3)); //Delete the selected element

		GeneralInformation.createCourseLeftModel(connection); //Initialize the Generic Model
		GeneralMethod.setLeftModel(GeneralInformation.getCourseLeftModel()); //Set the Generic Left JTable by the MyTableModel
		
		refreshSuperLeftTable();
		enableButton(false);
	}
	
	private void enableButton(boolean state)
	{
		getButtonDelete().setEnabled(state);
		getButtonModify().setEnabled(state);
	}
	
	public void createComponent()
	{		
		MyMouseListener mouseListener = new MyMouseListener();
		MyActionListener actionListener = new MyActionListener();
		
		tableLeft.addMouseListener(mouseListener);
		getButtonDelete().addActionListener(actionListener);
	}
	
	public void showComponent()
	{
		GraphicsSetting.setBackground(this, "image/Bg-Main.jpg", 0, 0, 800, 600);
	}
	
	private class MyMouseListener implements MouseListener
	{
		public void mouseClicked(MouseEvent arg0)
		{
			try
			{
				if(tableLeft.getSelectedRow() != -1)
				{
					enableButton(true);
					selectedRow = tableLeft.convertRowIndexToModel(tableLeft.getSelectedRow()); //Get the index of the selected row
					GeneralInformation.createCourseDescriptModel(connection, tableLeft, selectedRow);
					GeneralMethod.setDescriptModel(GeneralInformation.getCourseDescriptModel());
					refreshSuperDescriptTable();
				}
			}
			catch(CheckDataException | FormatScrollPaneException | LoadDriverException error)
			{
				TreatError.showError(error);
			}
		}
		
		public void mouseEntered(MouseEvent arg0){}
		public void mouseExited(MouseEvent arg0){}
		public void mousePressed(MouseEvent arg0){}
		public void mouseReleased(MouseEvent arg0){}
	}
	
	private class MyActionListener implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			try
			{
				if(arg0.getSource() == getButtonDelete())
					deleteCourse();
			}
			catch(NumberFormatException | InsertionDataException | CheckDataException | EraseDataException | Layer8TableException | FormatScrollPaneException | LoadDriverException error)
			{
				TreatError.showError(error);
			}
		}
	}
}